import json
from dataGenerator.ergongDevice.baseValues.ContantValues import  ContantValues
from dataGenerator.ergongDevice.baseValues.FluctuateValues import FluctuateValues
from flask import Blueprint
from common.contactStr import sqlContact, mqttMessageContact
from common.mqttUtil import on_mqtt_connect, publishMqttData
from common.mysqlUtil import exc_sql
from dataGenerator.ergongDevice.alarm.FrequencyFailure import FrequencyFailure
from dataGenerator.ergongDevice.CumulativeFlow.CumulativeFlow import CumulativeFlow
from dataGenerator.ergongDevice.ActivePower.ActivePower import ActivePower
from itertools import islice
from RootPath import RootPath
import os
from common.YmlUtil import YmlUtil
from dataGenerator.ergongDevice.frequencyValues.FrequencyValues import FrequencyValues

generPr = Blueprint("deviceGenerator", __name__)
path = os.path.join(RootPath.getRootPath(), "Application.yml")
devices_path = os.path.join(RootPath.getRootPath(), "devices.txt")
MQTTconf = YmlUtil().readYml(path, "mqtt_test_56")
MySQLconf = YmlUtil().readYml(path, "mysql_test_55")
# deviceID="17100005"


class deviceGenerator():
    def exc(self):
        print(" ======ergong device======")
        point_value = ContantValues().contantValues()
        outletPressureValue = FluctuateValues().FluctuateValues()
        FrequencyFailureValue = FrequencyFailure().FrequencyFailureValue()
        FrequencyValue = FrequencyValues().value()
        point_value.update(outletPressureValue)
        point_value.update(FrequencyFailureValue)
        point_value.update(FrequencyValue)

        #获取流量累计值
        flowVale = CumulativeFlow().readFlow()
        #先注释了，报错了
        point_value.update(flowVale)
        # #获取累计有功总电能
        powerVlaue = ActivePower().readPower()
        point_value.update(powerVlaue)
        print(point_value)
        on_mqtt_connect(MQTTconf)
        n = 100
        with open(devices_path, 'r') as f:
            for i in range(n):
                deviceID = next(f).strip('\n')
                sqldata = sqlContact(deviceID, point_value)
                mqttdata = json.dumps(mqttMessageContact(deviceID, point_value))
                publishMqttData(MQTTconf, mqttdata)
                exc_sql(sqldata, MySQLconf)

        # print(sqldata)
        # print(json.dumps(mqttdata))


if __name__ == '__main__':
    deviceGenerator().exc()
